package com.cp.weixin.crawler;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载文件
 */
public class DownFile implements Runnable {
	static Logger log = LogManager.getLogger();
	String fileUrl;
	String fileSavePath;
	String fileName;
	public DownFile(String fileUrl, String fileSavePath, String fileName) {
		this.fileUrl = fileUrl;
		this.fileSavePath = fileSavePath;
		this.fileName = fileName;
	}
	@Override
	public void run() {
		//log.warn("down img:"+imgUrl);
		try {
			//创建文件的目录
			File files = new File(fileSavePath);
			//判断文件目录是否存在，若不存在就创建一个
			if(!files.exists()){
				files.mkdirs();
			}
			//获取图片文件的下载地址
			URL url = new URL(fileUrl);
			//连接网络图片地址
			HttpURLConnection huc = (HttpURLConnection) url.openConnection();
			//获取连接的输出流
			InputStream is = huc.getInputStream();
			//创建文件
			File file = new File(fileSavePath + fileName);
			//创建输出流，写入文件
			FileOutputStream out = new FileOutputStream(file);
			int i = 0;
			while((i=is.read()) != -1){
				out.write(i);
			}
			out.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
